﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Auth.Sts;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using static Aliyun.Acs.Core.Auth.Sts.AssumeRoleResponse;

namespace Common.Utility
{
    public class OSSHelper
    {
        public static AssumeRole_Credentials GetSTSToken()
        {
            RedisUtil _redisUtil = new RedisUtil();
            var token = _redisUtil.Get<AssumeRole_Credentials>("STSToken");
            if (token != null)
            {
                return token;
            }
            //构建一个阿里云客户端，用于发起请求。
            //设置调用者（RAM用户或RAM角色）的AccessKey ID和AccessKey Secret。
            IClientProfile profile = DefaultProfile.GetProfile(AppSetting.GetAppSetting("Aliyun:OSS:RegionId"),
                AppSetting.GetAppSetting("Aliyun:OSS:AccessKeyId"), AppSetting.GetAppSetting("Aliyun:OSS:AccessKeySecret"));
            DefaultAcsClient client = new DefaultAcsClient(profile);

            //构建请求，设置参数。
            var request = new AssumeRoleRequest();
            request.RoleArn = AppSetting.GetAppSetting("Aliyun:OSS:RoleArn");
            request.RoleSessionName = AppSetting.GetAppSetting("Aliyun:OSS:RoleSessionName");

            try
            {
                var response = client.GetAcsResponse(request);
                if (response?.Credentials != null)
                {
                    _redisUtil.StringSet($"STSToken", JsonConvert.SerializeObject(response.Credentials), Convert.ToDateTime(response.Credentials.Expiration).AddMinutes(-5) - DateTime.Now);
                    return response.Credentials;
                }
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
                return null;
            }
            return null;
        }
    }
}
